package com.utonw.carloan.app;

import android.app.Activity;
import android.app.Application;

import com.utonw.carloan.global.CrashHandler;
import com.utonw.carloan.global.DRLogHelper;
import java.io.File;
import java.util.LinkedList;
import java.util.List;



/**
 * DarkRanger的Application
 * 
 * @author DarkRanger
 *
 */
public abstract class CrashApplication extends Application {

	// Activity列表
	private List<Activity> mActivityList = new LinkedList<Activity>();

	// drLog实例
	public DRLogHelper mDRLogHelper = DRLogHelper.getInstance();

	// 全局异常处理类的实例
	public CrashHandler mCrashHandler = new CrashHandler() {

		@Override
		public void initParams() {

		}

		@Override
		public void sendToServer(File logFile, File crashFile) {

		}

	};

	@Override
	public void onCreate() {

		super.onCreate();

		// 1、初始化DRLog参数
		initDRLogHelperParam();

		// 3、初始化全局异常处理类
		initCrashHandler();
	}

	/**
	 * 1、初始化DRLog参数，如： <br/>
	 * 
	 * {@link CrashApplication#getDrlog()} DRLog drLog = getDrlog(); <br/>
	 * {@link DRLogHelper#setLog4jFilePath(String)}
	 * drLog.setLog4jFilePath(Constants.LOG4J_FILE_PATH); <br/>
	 * {@link DRLogHelper#setType(cn.dr.lib.log.DRLogHelper.LogType)}
	 * drLog.setType(LogType.TYPE_LOG4J); <br/>
	 * 
	 * 只有在子类中完成initDRLogParam参数设置以后才能使用log
	 */
	protected abstract void initDRLogHelperParam();



	/**
	 * 3、初始化CrashHandler
	 */
	private void initCrashHandler() {
		// 3.1
		setHandler();

		// 3.2
		getCrashHandler().init(this);
	}

	/**
	 * 
	 * 3.1 调用以下方法为mCrashHandler设置实例<br/>
	 * <br/>
	 * 
	 * {@link #setCrashHandler(CrashHandler)}
	 */
	public abstract void setHandler();

	/**
	 * 获取DRLog单例
	 * 
	 * @return
	 */
	public DRLogHelper getDrLogHelper() {
		return mDRLogHelper;
	}

	public CrashHandler getCrashHandler() {
		return mCrashHandler;
	}

	public void setCrashHandler(CrashHandler mCrashHandler) {
		this.mCrashHandler = mCrashHandler;
	}

	/**
	 * 添加activity到App的mActivityList
	 * 
	 * @param activity
	 */
	public void addActivity(Activity activity) {
		this.mActivityList.add(activity);
	}

	/**
	 * 遍历mActivityList，结束每一个activity的声明周期
	 */
	private void finishActivityList() {
		for (Activity activity : mActivityList) {
			activity.finish();
		}
	}

	/**
	 * 完全退出程序
	 */
	public void appExit() {
		finishActivityList();
		// 正常退出
		System.exit(0);
	}

	/**
	 * 出现异常杀掉进程
	 */
	public void appKill() {

		finishActivityList();
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(1);
	}

}
